package com.example.spring_boot_demo.controller;

import com.aliyun.oss.OSSClient;
import com.example.spring_boot_demo.dto.UploadResult;
import com.example.spring_boot_demo.utils.AjaxResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

@RestController
@RequestMapping("/file")
public class OssController {
    @Resource
    private OSSClient ossClient;

    private static final String BUCKETNAME = "2024-05-31-test";
    /**
     * 使用 Bucket 域名
    */
    private String baseUrl = "https://2024-05-31-test.oss-cn-chengdu.aliyuncs.com/";

    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file){
        AjaxResult responseResult = AjaxResult.error("fail");

        //1.获得文件名字
        String fileName = file.getOriginalFilename();

        //2.获取文件流
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            //

            ossClient.putObject(BUCKETNAME,fileName,inputStream);

            //设置文件有效期  60天
            Date date = new Date(new Date().getTime()+ 1000*3600*24*60);
            //获取url
            URL url = ossClient.generatePresignedUrl(BUCKETNAME,fileName,date);

            //返回数据
            UploadResult fileResult = new UploadResult(fileName,baseUrl+fileName);
            //
            responseResult=AjaxResult.success(fileResult);
            return responseResult;
        }catch (IOException e){
            e.printStackTrace();
        }
        return responseResult;
    }

    //删除文件
    @PostMapping("/del")
    public AjaxResult del(String fileName){
        ossClient.deleteObject(BUCKETNAME,fileName);
        return AjaxResult.success("删除成功");
    }
}
